﻿package com.reyco1.manager
{
    import flash.events.*;
    import flash.net.FileReference;
    import flash.net.URLRequest;
    import com.reyco1.events.FileEvent;
    import com.reyco1.util.MathUtil;
    import com.reyco1.extension.DispatchExtension;
	import flash.events.IOErrorEvent;
	
    public class UploadManager extends DispatchExtension
    {
        /*
        variables
        */
        
        /**
        * path to the upload server side script
        */        
        public var UPLOAD_URL:String;
        private var objFileReference:FileReference;

        public function UploadManager() 
        {
        	this.init();
        }

        private function init():void {
            this.objFileReference = new FileReference();
            this.objFileReference.addEventListener(Event.SELECT, selectHandler);
            this.objFileReference.addEventListener(Event.OPEN, openHandler);
            this.objFileReference.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            this.objFileReference.addEventListener(Event.COMPLETE, completeHandler);
			this.objFileReference.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        }

        /**
         * Cancel current upload
         * 
         */        
        public function cancelUpload():void 
        {
            this.objFileReference.cancel();
        }

        /**
         * Opens the browse dialog box which allows the user to choose which file to upload to the server
         * 
         */        
        public function uploadFile():void 
        {
            this.objFileReference.browse();
        }

        private function selectHandler(event:Event):void {
            var request:URLRequest = new URLRequest();
            request.url = UPLOAD_URL;
            this.objFileReference.upload(request);
            this.dispatchEvent(new FileEvent(FileEvent.UPLOAD_START, {}));
        }

        private function openHandler(event:Event):void 
        {
        }

        private function progressHandler(event:ProgressEvent):void 
        {
        	var percent:Number = MathUtil.percentage(event.bytesLoaded, event.bytesTotal);
        	this.dispatchEvent(new FileEvent(FileEvent.UPLOAD_PROGRESS, {percent:percent}));
        }

        private function completeHandler(event:Event):void 
        {
			this.dispatchEvent(new FileEvent(FileEvent.UPLOAD_COMPLETE, {}));
        }
		
		private function ioErrorHandler(event:IOErrorEvent):void 
		{
            this.dispatchEvent(new FileEvent(FileEvent.UPLOAD_ERROR, {error:event}));
        }
    }
}